import api from "../../utils/api";
import Utils from "../../utils/utils";
let timer: any
// pages/search/search.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wordsList:[] as string[],//热搜列表
    page:1 as number,
    pageSize:10 as number,
    search:'' as string,
    totalCount: 0  as number,
    commodityList:[] as CommodityModel[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getHotSearchList();
  },
  // 获取热搜列表
  getHotSearchList(): void {
    api.index.getHotSearchList().then(res => {
      if(res.data.code == "000") {
        this.setData({
          wordsList: res.data.data
        })
      }else {
        wx.showToast({
          title:res.data.message as string,
          icon:"error"
        })
      }
    })
  },
  // 输入改变
  inputChange(e:any): void {
    if(timer) {
      clearTimeout(timer)
    }
    this.setData({
      search: e.detail.value
    })
    timer = setTimeout(() => {
      this.search()
    }, 500)
  },
  search(type:string = 'reset'): void {
    const {page, pageSize, search, commodityList} = this.data
    // 没有关键字就不搜索
    if(!search) {
      this.setData({
        commodityList:[]
      })
      return 
    }
    const params:CommodityGetCommodityListParam = {
      page: type == "add"? page: 1,
      pageSize,
      search
    }
    api.commodity.getCommodityList(params).then(res => {
      if(res.data.code == "000") {
        if (res.data.data && res.data.data.list) {
          res.data.data.list.forEach(item => {
            item.price = Utils.priceToYuan(item.price as number)
            item.originalPrice = Utils.priceToYuan(item.originalPrice as number)
          })
          this.setData({
            commodityList: type == "add" ? [...commodityList, ...res.data.data.list] : res.data.data.list,
            totalCount: res.data.data.totalCount,
            page: page + 1
          })
        }
      }else {
        wx.showToast({
          title: res.data.message as string,
          icon:"error"
        })
      }
    })
  },
  toDetail(e:any): void {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "/pages/malldetail/malldetail?type=normal&id=" + id
    })
  },
  // 选择搜素词
  changeSearch(e:any): void {
    this.setData({
      search: e.currentTarget.dataset.item
    })
    this.search()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.totalCount == this.data.commodityList.length) {
      return
    }
    this.search("add");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})